//
//  CarInfoVC.swift
//  SlaughterClient
//
//  Created by 邱仙凯 on 2022/3/24.
//  Copyright © 2022 zwb. All rights reserved.
//

import UIKit
 
class ZyaCarInfoVC: UITableViewController {
    
    var id_key = ""
    var voc_cd = ""
    var processid = ""
    var todotype = ZyaTodoType.normal
     var helper = ZyaTenderHelper()
    var model = ZyaCarInModel(JSON:["":""])!
    lazy var dateTimePick:DateTimePicker = {
        let v = DateTimePicker()
        return v
    }()
    lazy var submitButton: KSUIButton = {
        let button = KSUIButton(titlex: "保存")
        
        return button
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "车辆信息"
        tableView.estimatedRowHeight = 100
        tableView.separatorStyle = .none
        tableView.rowHeight = UITableView.automaticDimension
        
        tableView.tableFooterView = UIView()
        tableView.backgroundColor = Theme.awModuleBgColor
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
  
        
        self.tableView.register(ZyaCarInfoCell.self, forCellReuseIdentifier: ZyaCarInfoCell.identifier)
        tableView.register(GlobalAddTableCell.self, forCellReuseIdentifier: GlobalAddTableCell.identifier)

        self.tableView.register(GeneralSepeCell.self, forCellReuseIdentifier: GeneralSepeCell.identifier)
        self.tableView.register(ZyaAuditSectinoHeader.self, forHeaderFooterViewReuseIdentifier: ZyaAuditSectinoHeader.identifier)
        self.tableView.register(ZyaGeneralAuditCell.self, forCellReuseIdentifier: ZyaGeneralAuditCell.identifier)
        let v = UIView(frame: CGRect(x: BgLeading, y: 0, width: KSGlobal.screenW - BgLeading * 2, height: ItemBtnHeight + 15))
        v.backgroundColor = .clear
         v.addSubview(submitButton)
        submitButton.button.addTouchUpInSideAction { _ in
            self.saveAction()
        }
        submitButton.ks_y = v.ks_y + 15
        tableView.tableFooterView = v
        KSNetwork.shared.doRequest(API.queryZbCarInfo(id_key: id_key)) { (data:BaseResult<ZyaCarInModel>) in
            if data.flag == TRUE {
                if let info = data.infoObjCombine {
                    self.model = info
                    self.tableView.reloadData()
                }
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
 
    }
    func saveAction() {
        view.endEditing(true)
         let vali = Validation()
        
       
            vali.expression(self.model.carInfo.count > 0, msg: "车辆不为空")
            for i in 0..<self.model.carInfo.count {
                vali.required(value: self.model.carInfo[i].zCarNo, msg: "第\(i + 1)条，车牌号不能为空!")
                vali.required(value: self.model.carInfo[i].zDriverNm, msg: "第\(i + 1)条，司机姓名不能为空!")
                vali.required(value: self.model.carInfo[i].zDriverTel, msg: "第\(i + 1)条，联系方式不能为空!")
                 vali.required(value: self.model.carInfo[i].zArriveTm, msg: "第\(i + 1)条，到达时间不能为空!")

            }
 
        guard vali.validate() else {
            return
        }
        var json = self.model.carInfo.compactMap { dictionaryToJson($0.dictionaryRepresentation()) }.joined(separator: ",")
        json = "[\(json)]"
        var api:API!
          api = API.updateZbCarInfo(data: json)
 
        KSNetwork.shared.doRequest(api) { (data: BaseResult<OperateResult>) in
            if data.flag == TRUE {
               
                self.navigationController?.popViewController(animated: true)
                
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
    }
    
}

extension ZyaCarInfoVC {
    
    // MARK: - TableView DataSource And Delegate
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 2 + model.carInfo.count + 1
    }
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        if section == 0 {
            return self.model.zbOpen ? self.model.zbArrayNew.count : 0
        } else if section == 1 {
            return self.model.cjOpen ?  self.model.cjArrayNew.count : 0
        } else if section < self.model.carInfo.count + 2 {
            return self.model.carInfo[section - 2].openx ? 1 : 0
         } else {
            return 1
        }
        
        
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      
        if indexPath.section < 2 {
            let cell = tableView.dequeueReusableCell(withIdentifier: ZyaGeneralAuditCell.identifier, for: indexPath) as! ZyaGeneralAuditCell
            var tempArr:ZyaZbArrayNew!
            if indexPath.section == 0 {
                 tempArr = model.zbArrayNew[indexPath.row]
            } else {
                 tempArr = model.cjArrayNew[indexPath.row]
            }
         cell.titlex = tempArr.name.unwrap
        cell.contentx = tempArr.value.unwrap
        cell.conType = .content
             return cell
        } else if indexPath.section < self.model.carInfo.count + 2 {
            let cell = tableView.dequeueReusableCell(withIdentifier: ZyaCarInfoCell.identifier, for: indexPath) as! ZyaCarInfoCell
             
            cell.one = model.carInfo[indexPath.section - 2]
            cell.item1.textValueChangeClo = { [indexPath] str in
                self.model.carInfo[indexPath.section - 2].zCarNo = str
            }
            cell.item2.textValueChangeClo = { [indexPath] str in
                self.model.carInfo[indexPath.section - 2].zDriverNm = str
            }
            cell.item3.textValueChangeClo = { [indexPath] str in
                self.model.carInfo[indexPath.section - 2].zDriverTel = str
            }
            cell.item4.actionClosure = { [indexPath]  in
                self.dateTimePick.resultClosure = { str in
                    self.model.carInfo[indexPath.section - 2].zArriveTm = str
                     self.tableView.reloadData()
                }
//                UIApplication.shared.keyWindow!.rootViewController!.view!.addSubview(self.dateTimePick)
                self.dateTimePick.present()
            }
             return cell
            
         } else  {  // +
             let cell = tableView.dequeueReusableCell(withIdentifier: GlobalAddTableCell.identifier, for: indexPath) as! GlobalAddTableCell
             cell.titleLab.text = "+  添加车辆信息"
             return cell
         }
            
    
        
    }
    
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section < 2 {
            return UITableView.automaticDimension
         } else if indexPath.section < self.model.carInfo.count + 2 {
            return 190
        } else {
            return 45
        }
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
 
        if indexPath.section == self.model.carInfo.count + 2 {
           
            var one = ZyaCarInfo(JSON:[ "":""])!
            one.zBidId = self.id_key
             self.model.carInfo.append(one)
             self.tableView.reloadData()
        }
         
    }
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section < self.model.carInfo.count + 2 {
            return 50
        } else {
            return 0
        }
    }
    
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        
        guard let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: ZyaAuditSectinoHeader.identifier) as? ZyaAuditSectinoHeader else {
            fatalError()
        }
        let tap = UITapGestureRecognizer()
        tap.numberOfTapsRequired = 1
        tap.addTap { [unowned self] _ in
            if section == 0 {
                self.model.zbOpen = !self.model.zbOpen
             } else if section == 1 {
                self.model.cjOpen = !self.model.cjOpen
             } else {
                 self.model.carInfo[section - 2].openx = !self.model.carInfo[section - 2].openx
             }
            let set = IndexSet(integer:section)
            tableView.reloadSections(set, with:UITableView.RowAnimation.automatic)
        }
        
        headerView.addGestureRecognizer(tap)
        var ttt = ""
        if section == 0 {
            ttt = "出价信息"
            headerView.del.isHidden = true
            if self.model.zbOpen {
                headerView.arrow.setBackgroundImage(UIImage(named: "arrow_down"), for: .normal)
            } else {
                headerView.arrow.setBackgroundImage(UIImage(named: "arrow_right"), for: .normal)
            }
        } else if section == 1 {
            ttt = "成交信息"
            headerView.del.isHidden = true
            if self.model.cjOpen {
                headerView.arrow.setBackgroundImage(UIImage(named: "arrow_down"), for: .normal)
            } else {
                headerView.arrow.setBackgroundImage(UIImage(named: "arrow_right"), for: .normal)
            }
        } else if section < self.model.carInfo.count + 2 {
            ttt = "车辆信息"
            headerView.del.isHidden = false
            if self.model.carInfo[section - 2].openx {
                headerView.arrow.setBackgroundImage(UIImage(named: "arrow_down"), for: .normal)
            } else {
                headerView.arrow.setBackgroundImage(UIImage(named: "arrow_right"), for: .normal)
            }
        }
        
         headerView.lab.text = ttt
        headerView.deleteClo = { [section] in
            alertUtil(self, title: "确认删除", operateS: [nameAction(name: "确定", action: { _ in
                let idk = self.model.carInfo[section - 2].idKey.unwrap
                if idk != "" {
                    KSNetwork.shared.doRequest(API.delZbCarInfo(id_key: idk)) { (data:BaseResult<ZyaCarInModel>) in
                        if data.flag == TRUE {
                            self.model.carInfo.remove(at: section - 2)
                            self.tableView.reloadData()
                        } else {
                            KSToast(data.errorCombine.unwrap)
                        }
                    }
                } else {
                    self.model.carInfo.remove(at: section - 2)
                    self.tableView.reloadData()
                }
               
                
            })])
           
        }
        return headerView
        
    }
    
    
}
